import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { Task } from '../task/task.model';

import { ModalDirective } from 'ngx-bootstrap/modal';

import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-teacher',
  templateUrl: './teacher.component.html',
  styleUrls: ['./teacher.component.css',
        '../task/task.component.css',
        '../app.component.css']
})
export class TeacherComponent implements OnInit {

    private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
    url = 'http://edu.xk.com/xkapi'; 
    addOrEdit:string = 'add';

    data = [];
    array = [];

    size: number = 10;    
    index: number;     //要先声明 

    searchCode:string = '';
    searchTeacher:string = '';
    searchContact:string = '';
    id: number = 0;
    
    activeMenu = 'teacher';

    code:string = '';
    name:string = '';
    contact:string = '';
    courses:string = '';
    communities:string = '';
    areaId:string = '';
    content:string = '';
    deleteId : number = 0;
    isEmpty:boolean = false;
    /* 分页，start*/
    maxSize: number = 5;
    bigTotalItems: number = 50000; //总数
    bigCurrentPage: number = 1; //当前页
    numPages: number = 0;   //总页数
   
    pageChanged(event: any): void {
      this.bigCurrentPage = event.page;
      this.getList(event.page, 10);
      console.log('Page changed to: ' + event.page);
      console.log('Number items per page: ' + event.itemsPerPage);
    }
    /* 分页，end*/
    constructor(private http: HttpClient){ }

    ngOnInit() {
      this.getList(1,10)  //要this
      this.getCommunities();
    }

    getList(pagenumber, pagesize){

        let reqParam = `page=${pagenumber}&size=${pagesize}&code=${this.searchCode}&name=${this.searchTeacher}&contact=${this.searchContact}`;
        return this.http.post(`${this.url}/teacher/findAllByQueryAndPage`, reqParam, { 'headers': this.headers} ).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.data = result['data'];
                      this.array = this.data['content'];
                      this.bigTotalItems = this.data['totalElements']; //总数
                      this.numPages = this.data['totalPages'];   //总页数
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }

    getCommunities(){
      return this.http.get(`${this.url}/area/findAll`).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.communities = result['data'];
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }
    // search
    search() {
        this.bigCurrentPage = 1;
        this.getList(1, 10);
    }
    clear() {
        this.searchCode = '';
        this.searchTeacher = '';
        this.searchContact= '';

        this.search();
    }

    //添加和编辑 提交按钮
    onSubmit(id, areaId, code, name, contact, courses, content, addModal):void {
        let reqUrl = this.addOrEdit === 'add' ? `${this.url}/teacher/add` : `${this.url}/teacher/update`;
        let coursesStr: string = courses.trim().replace(/\s/g, ",").replace(/，/g, ",");
        if (!(areaId && name && contact && courses && content)) {
            this.isEmpty= true;
            return;
        }
        this.isEmpty= false;
        this.http.get(`${reqUrl}?id=${id}&code=${code}&areaId=${areaId}&name=${name}&contact=${contact}&lessonNames=${coursesStr}&content=${content}`).subscribe(
          result => {
            if(result) {
              if (result['status'] == 200) {
                  this.getList(1, 10); //要this
                  this.bigCurrentPage = 1;
                  addModal.hide();
              } else {
                  console.log(result['desc']);
              }
            }
          }
        );
    }
    ngChangedFn():void {
        this.isEmpty = false;
    }
    //添加
    addNew(addModal) {
        addModal.show();

        this.addOrEdit = 'add';
        this.id = 0;
        this.name = '';
        this.code = '';
        this.contact = '';
        this.courses = '';
        this.areaId = '';
        this.content = '';
    }
    // 编辑 按钮
    edit(item, addModal) {  
        console.log('item:');
        console.log(item);

        addModal.show();
        
        this.addOrEdit = 'edit';
        this.id = item.id;
        this.name = item.name;
        this.code = item.code;
        this.contact = item.contact;
        this.courses = item.lessonNames;
        this.areaId = item.areaId;
        this.content = item.content;
    }
    //删除按钮
    delete(item, deleteModal){  
        deleteModal.show();
        console.log('delete');
        this.deleteId= item.id;
        
    }
    //删除 确认
    deleteConfirm(item,deleteModal) {  
        console.log('item:');
        console.log(item);
        return this.http.get(`${this.url}/teacher/delete?id=${this.deleteId}`).subscribe(
          result => {
              if(result) {
                this.getList(1, 10)  //要this
                this.bigCurrentPage = 1;
                deleteModal.hide();
              } else {
                  console.log(result['desc']);
              }
          }
      );
    }
}

export class DemoDatePickerPopupComponent {
    minDate = new Date(2017, 5, 10);
    maxDate = new Date(2018, 9, 15);

    bsValue: Date = new Date();
    bsValueEnd: Date = new Date();

}
export class DemoTimepickerCustomComponent {
    hstep: number = 1;
    mstep: number = 15;
   
    mytime: Date = new Date();
    mytimeEnd: Date = new Date();
    options: any = {
        hstep: [1, 2, 3],
        mstep: [1, 5, 10, 15, 25, 30]
    };
}
